const express = require('express');
const router = express.Router();
const Bottle = require('../models/Bottle');
const { sendMail } = require('../config/email');
const { Op } = require('sequelize');
const sequelize = require('../config/database');
const User = require('../models/User');
const Message = require('../models/Message');

// 扔漂流瓶
router.post('/throw', async (req, res) => {
    try {
        const { message, email } = req.body;

        if (!message || !message.trim()) {
            return res.status(400).json({ error: '消息不能为空' });
        }

        const bottle = await Bottle.create({
            message,
            email,
            status: 'active'
        });

        res.json({ 
            success: true, 
            message: '漂流瓶已成功扔出',
            bottleId: bottle.id 
        });
    } catch (error) {
        console.error('扔漂流瓶失败:', error);
        res.status(500).json({ error: '扔漂流瓶失败' });
    }
});

// 捡漂流瓶
router.post('/pick', async (req, res) => {
    try {
        // 随机获取一个未被捡起的漂流瓶
        const bottle = await Bottle.findOne({
            where: {
                status: 'active'
            },
            order: sequelize.random()
        });

        if (!bottle) {
            return res.status(404).json({ error: '海里空空如也，等待有缘人扔瓶子吧~' });
        }

        // 更新漂流瓶状态
        await bottle.update({
            status: 'picked',
            pickTime: new Date()
        });

        // 返回漂流瓶内容
        res.json({
            success: true,
            bottle: {
                id: bottle.id,
                message: bottle.message,
                timestamp: bottle.createdAt
            }
        });
    } catch (error) {
        console.error('捡漂流瓶失败:', error);
        res.status(500).json({ error: '捡漂流瓶失败' });
    }
});

// 回复漂流瓶
router.post('/reply/:id', async (req, res) => {
    try {
        const { message, email } = req.body;
        const bottleId = req.params.id;

        const bottle = await Bottle.findByPk(bottleId);
        if (!bottle) {
            return res.status(404).json({ error: '漂流瓶不存在' });
        }

        if (!bottle.email) {
            return res.status(400).json({ error: '该漂流瓶无法回复' });
        }

        // 发送回复邮件
        await sendMail({
            to: bottle.email,
            subject: '你的漂流瓶收到了回复',
            message: message,
            from: email || '匿名用户'
        });

        // 查找收件人用户
        const user = await User.findOne({
            where: { email: bottle.email }
        });

        // 如果用户存在，创建消息通知
        if (user) {
            await Message.create({
                userId: user.id,
                type: 'bottle_reply',
                content: message,
                from: email || '匿名用户'
            });
        }

        res.json({ success: true, message: '回复已发送' });
    } catch (error) {
        console.error('回复漂流瓶失败:', error);
        res.status(500).json({ error: '回复失败' });
    }
});

// 获取每日统计
router.get('/daily-stats', async (req, res) => {
    try {
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        const stats = await Bottle.findAndCountAll({
            where: {
                createdAt: {
                    [Op.gte]: today
                }
            },
            attributes: ['status']
        });

        res.json({
            total: stats.count,
            active: stats.rows.filter(b => b.status === 'active').length,
            picked: stats.rows.filter(b => b.status === 'picked').length
        });
    } catch (error) {
        console.error('获取统计失败:', error);
        res.status(500).json({ error: '获取统计失败' });
    }
});

module.exports = router; 